#!/usr/bin/env bash
set -euo pipefail

# Constants
readonly SSH_CMD='ssh -A -o StrictHostKeyChecking=no -p 22'
readonly GAME="xnh5"
readonly RSYNC_PASSWORD='PVi#sFyvZC%jeQTN'
readonly BACKUP_DIR="/data/backup/db/$(date +%F)"

# Helper functions
function validate_arguments() {
  if [[ $# -lt 2 ]]; then
    echo "Usage: $0 <agent> <sid> [optional_args]"
    exit 1
  fi
}

function get_config_path() {
  local agent=$1
  local sid=$2
  echo "/data/workspace/$GAME/${agent}/server/script/game/xnh5_${agent}_game_${sid}/main.config"
}

function is_game_running() {
  local node_name=$1
  pgrep -f "${node_name}\b" >/dev/null
}

function run_with_check() {
  local cmd=$1
  local success_msg=$2
  local error_msg=$3

  if $cmd; then
    echo "$success_msg"
    return 0
  else
    echo "$error_msg" >&2
    return 1
  fi
}

# Game operations
function start_game() {
  validate_arguments "$@"
  local agent=$1 sid=$2
  local config=$(get_config_path "$agent" "$sid")
  local node_name="${GAME}_${agent}_game_${sid}"
  local game_dir="/data/workspace/$GAME/${agent}/"

  [[ -f "$config" ]] || { echo "游戏不存在，请确认!"; exit 1; }

  if ! is_game_running "$node_name"; then
    cd "${game_dir}/server/script/"
    run_with_check \
      "sh ctl.sh start game $sid" \
      "游戏开启成功" \
      "游戏开启失败"
  else
    echo "游戏已经开启"
    exit 1
  fi
}

function stop_game() {
  validate_arguments "$@"
  local agent=$1 sid=$2 force=${3:-n}
  local config=$(get_config_path "$agent" "$sid")
  local node_name="${GAME}_${agent}_game_${sid}"

  [[ -f "$config" ]] || { echo "游戏不存在，请确认!"; exit 1; }

  if is_game_running "$node_name"; then
    cd "/data/workspace/$GAME/${agent}/server/script/"
      sh ctl.sh stop game $sid 
  fi 
  return 0
}

function backup_database() {
  local config=$1
  local db_pass=$(grep "db_pass" "$config" | grep -v log | awk -F'"' '{print $2}')
  local db_host=$(grep "db_host" "$config" | awk -F, '{print $3}' | awk -F\" '{print $2}')
  local db_name=$(grep "db_name" "$config" | grep -v log | awk -F'"' '{print $2}')

  mkdir -p "$BACKUP_DIR"
  chmod -R 777 "$BACKUP_DIR"
  /usr/local/mysql/bin/mysqldump -uroot -h"${db_host}" -p"${db_pass}" "$db_name" >"${BACKUP_DIR}/${db_name}_$(date +%F).sql"
}


function update_time {
  validate_arguments "$@"
  local agent=$1 sid=$2
  local config=$(get_config_path "$agent" "$sid")
  local open_time="$3 $4"
  local s_time=($(echo $open_time | sed 's/-/ /g' | sed 's/:/ /g'))
  sed -i "s/\({open_time, \)\(.*\)/\1{${s_time[0]}, ${s_time[1]}, ${s_time[2]}}}/g" $config  
  [ $? -eq 0 ] && echo "开服时间修改成功" || (echo "开服时间修改失败" && /bin/false) || exit 1
  stop_game ${agent} ${sid}
  stop_game ${agent} ${sid}
  stop_game ${agent} ${sid}
  bakdir="/data/workspace/$GAME/${agent}/server/script/game/xnh5_${agent}_game_${sid}/data_`date +%F_%T`"
  mv /data/workspace/$GAME/${agent}/server/script/game/xnh5_${agent}_game_${sid}/data    $bakdir
  sudo mkdir -p /data/workspace/$GAME/${agent}/server/script/game/xnh5_${agent}_game_${sid}/data 
  sudo chmod -R 777 /data/workspace/$GAME/${agent}/web/${agent}_s${sid}/web/runtime/  #授权runtime写权限
  start_game ${agent} ${sid}
  echo "ok"
}

function truncate_server() {
  validate_arguments "$@"
  local agent=$1 sid=$2
  if [ $3 == "y" ];then 
     install_game=1
  else
     install_game=0
  fi 
  # shellcheck disable=SC2107
  
  local config=$(get_config_path "$agent" "$sid")
  
  #停三次防止未关闭
  stop_game "$agent" "$sid" y
  sleep 1
  stop_game "$agent" "$sid" y
  sleep 1
  stop_game "$agent" "$sid" y
  backup_database "$config"

  cd "/data/workspace/$GAME/${agent}/server/script/"
  local db_pass=$(grep "db_pass" "$config" | grep -v log | awk -F'"' '{print $2}')
  local db_host=$(grep "db_host" "$config" | awk -F, '{print $3}' | awk -F\" '{print $2}')
  local db_name=$(grep "db_name" "$config" | grep -v log | awk -F'"' '{print $2}')
  local role_num=$(/usr/local/mysql/bin/mysql -uroot -h"${db_host}" -p"${db_pass}"  -NBe "select count(1) from ${db_name}.role;" 2>/dev/null)
   
  local node_name="${GAME}_${agent}_game_${sid}"
  bakdir=/data/backup/game/truancate/`date +%F`
  mkdir -pv $bakdir
  /bin/cp -ar game/$node_name $bakdir/
  local cmd="sh ctl.sh uninstall  game $sid ${role_num}"
  echo $cmd;
  run_with_check \
    "sh ctl.sh uninstall  game $sid ${role_num} |grep -q \"${node_name}@127.0.0.1已经删除\"" \
    "服务器清档成功" \
    "服务器清档失败"
  if [ $install_game -eq 1 ];then
      echo y | sh ctl.sh install game $sid 
      #还原配置
      /bin/cp -ar $bakdir/$node_name/main.config   game/${node_name}/
      sh ctl.sh start game $sid 
      if [ $? -eq 0 ];then
          echo "ok"
      else
          echo 'failed'
     fi 
  fi
}

function install_game(){
   validate_arguments "$@"
  local agent=$1 sid=$2 
   local opentime="$3 $4"
   local config=$(get_config_path "$agent" "$sid")
   cd "/data/workspace/$GAME/${agent}/server/script/" 
   local s_time=($(echo $opentime | sed 's/-/ /g' | sed 's/:/ /g'))
   echo y |sh ctl.sh install game $sid
   sed -i "s/\({open_time, \)\(.*\)/\1{${s_time[0]}, ${s_time[1]}, ${s_time[2]}}}/g" $config
   sleep 1 
   sh ctl.sh start game $sid 
   
}


function cat_game_open_time(){
   validate_arguments "$@"
  local agent=$1 sid=$2
  local config=$(get_config_path "$agent" "$sid")
  open_date=$(grep open_time $config | awk -F[{}] '{print $3}' | sed 's/ //g' | sed 's/,/-/g')
  echo $(date -d $open_date +%s)

}


# Main execution
if [ $# -lt 1 ];then
echo -e "
   bash $0 start_game xiwan 1
   bash $0 stop_game xiwan 1
   bash $0 update_time xiwan 1 "2025-05-01 10:00:00"
   bash $0 truncate_server xiwan 1
"
exit 10
fi
case $1 in
  start_game) shift;  start_game "$@" ;;
  stop_game)shift;  stop_game "$@" ;;
  update_time) shift; update_time "$@" ;;
  rsync_server_log) shift; rsync_server_log "$@" ;;
  truncate_server) shift; truncate_server "$@"  y;;
  cat_game_open_time) shift; cat_game_open_time "$@" ;;
  uninstall_game) shift; uninstall_game "$@" ;;
  *) echo "参数错误"; exit 1 ;;
esac

